
<template>
<!-- 面包屑 -->
  <div>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item>首页</el-breadcrumb-item>
    <el-breadcrumb-item>人员管理</el-breadcrumb-item>
    <el-breadcrumb-item><b>学生信息管理</b></el-breadcrumb-item>
  </el-breadcrumb>
  </div>
<!--  搜索框-->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="姓名" prop="sname">
        <el-input v-model="searchFormModel.sname" placeholder="请输入学生姓名" clearable />
      </el-form-item>
      <el-form-item label="院系" prop="dept">
        <el-select
            v-model="searchFormModel.dept"
            placeholder="请选择院系"
            clearable  style="width:140px">
          <el-option
              v-for="item in deptValue"
              :key="item.dept"
              :label="item.deptname"
              :value="item.deptid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="sid">
        <el-input v-model="searchFormModel.sid" placeholder="请输入学号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOnSubmit">
          <el-icon><Search /></el-icon>  查询
        </el-button>
        <el-button type="danger"   @click="deleteSelectedRows()">
          <el-icon><Delete /></el-icon>  批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </div>
<!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="stuInfo" stripe border style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" v-if="show"/>
      <el-table-column prop="sid" label="学号"/>
      <el-table-column prop="sname" label="姓名"/>
      <el-table-column prop="gender" label="性别"  />
      <el-table-column prop="dept" label="院系"  :formatter="attributeFormatter"/>
      <el-table-column prop="address" label="地址"  />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="photourl" label="头像" />
      <el-table-column prop="phone" label="联系方式" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="tableEditHandler(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="tableDeleteHandler(scope.$index, scope.row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,8]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
<!--  编辑-->
  <el-dialog v-model="dialogEditState" title="修改学生信息" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit"
               :rules="formEditRules"
               label-width="120px">
        <el-form-item prop="sid" label="学号">
          <el-input v-model="formEdit.sid"  disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="formEdit.email" ></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="联系方式">
          <el-input v-model="formEdit.phone" maxlength="11" show-word-limit></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {ArrowRight, Delete, Edit,Search,TopRight,BottomLeft} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/freshman";
import {ElMessage, ElMessageBox} from "element-plus";
onMounted(()=>{
  getStu();
  getDept();
})
//分页
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const stuInfo=ref([]);
//对应的值
const deptValue=ref([]);
const getDept=()=>{
  request({
    url:'/dept/all',
    method:'get'
  }).then((req)=>{
    console.log(req)
    if (200==req.data.errorCode){
      deptValue.value=req.data.data;
    }
  })
}
const attributeFormatter=(row, column, cellValue)=> {
  for (let i=0;i<deptValue.value.length;i++){
    if (cellValue== deptValue.value[i].deptid){
      return deptValue.value[i].deptname
    }
  }
}
//搜索
const searchFormRef=ref();
const searchFormModel=reactive({
  sname:'',
  sid:'',
  dept:''
})
const getStu=()=>{
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    // 初始时不包含其他参数
  };
  if (searchFormModel.sname && searchFormModel.sname.trim() !== ''){
    params.sname=searchFormModel.sname.trim();
  }
  if (searchFormModel.sid && searchFormModel.sid.trim() !== ''){
    params.sid=searchFormModel.sid.trim();
  }
  if (searchFormModel.dept){
    params.dept=searchFormModel.dept;
  }
  request({
    url:'/admin/freshman/page',
    method:'get',
    params,
  }).then((req)=>{
    if (200==req.data.errorCode){
      stuInfo.value=req.data.data.records;
      totals.value=req.data.data.total;
    }
  })
}
const searchOnSubmit=()=>{
  getStu()
}
const handleSizeChange = (val) => {
  pageSize.value=val;
  getStu()
}
const handleCurrentChange = (val) => {
  currentPage.value=val;
  getStu()
}

//删除一条
const tableDeleteHandler = (rowIndex , rowData) => {
  ElMessageBox.confirm(
      '确认删除 : ' +rowData.id,
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {//点击了删除按钮
    request({
      method:'delete',
      url:'/admin/freshman/delete/'+rowData.id
    }).then(req=>{
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
       getStu();
      }
    })
  })
      .catch(() => {//点击了取消按钮
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//删除多个
const selectedRows=ref([])
const handleSelectionChange=(rows)=>{
  selectedRows.value = rows;
}
const deleteSelectedRows=()=>{
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: '请选择要删除的记录',
      type: 'warning',
    });
    return;
  }

  ElMessageBox.confirm(
      '此操作将永久删除选中的记录, 是否继续?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 获取所有选中的ID
        const ids = selectedRows.value.map(row => row.id).join(',');
        request({
          method: 'delete',
          url: '/admin/freshman/dels',
          params:{id:ids}
        }).then((response) => {
          console.log(response)
          if (response.data.errorCode == 200) {
            ElMessage({
              type: 'success',
              message: '批量删除成功',
            });
            getStu();
          }
        }).catch(() => {
          ElMessage({
            type: 'error',
            message: '批量删除失败',
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
};
//编辑
const formEditRef = ref()
const formEditData = {
  sid:'',
  address:'',
  email:'',
  phone:''
}
//编辑的校验规则
const formEditRules={
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^\d{11}$/, message: '电话号码必须为11位数字', trigger: 'blur' }
  ]
};

// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.sid = rowData.sid
  formEdit.address = rowData.address
  formEdit.email = rowData.email
  formEdit.phone = rowData.phone
  dialogEditState.value = true
}
const dialogEditState = ref(false)
const dialogEditOnSubmit = () => {
  formEditRef.value.validate((valid) => {
    if (valid) {
      // 数据提交到服务器
      request({
        url: '/fresh/update',
        method: 'put',
        data: JSON.stringify(formEdit),
        headers: {'content-type': "application/json;charset=UTF-8"}
      }).then(response => {
        if (response.data.errorCode === 200) {
          ElMessage({
            type: 'success',
            message: '修改成功！',
          });
          getStu();
        } else {
          ElMessage({
            type: 'error',
            message: '修改失败：' + response.data.msg,
          });
        }
      }).catch(error => {
        console.error('请求失败:', error);
        ElMessage({
          type: 'error',
          message: '请求失败',
        });
      }).finally(() => {
        dialogEditState.value = false;
      });
    } else {
      ElMessage({
        type: 'error',
        message: '表单验证失败',
      });
    }
  });
}
const dialogEditOnReset = () => {
  Object.assign(formEdit , formEditData)
  dialogEditState.value = false
}
</script>

<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.page{
  margin-left: 30%;
}
</style>